Php/consistent hashing
提供: 初心者エンジニアの簡易メモ
サンプル
<?php
/**
* 基底DAO
*
* @ex
* // キャッシュ取得
* if ($result = $this->getCache($this->_makeCacheKey(array($this->_cacheNameSpace, $id)))) {
* return $result;
* } else {
* // 処理実行
*
* // キャッシュ設定
* $this->setCache($this->_makeCacheKey(array($this->_cacheNameSpace, $id)), $result);
* return $result;
* }
*
* -memcached.ini
* memcached.1.host = "localhost"
* memcached.1.port = "11211"
* memcached.2.host = "localhost2"
* memcached.2.port = "11211"
*/
class AbstractDao extends Zend_Db_Table_Abstract
{
// キャッシュ
private $_cache;
// キャッシュnamespace
protected $_cacheNameSpace;
/**
* キャッシュコネクション生成
*/
public function createCacheConnection()
{
try {
// configロード
$config = new Zend_Config_Ini(APPLICATION_PATH . '/../configs/memcached.ini', APPLICATION_ENV);
// キャッシュロード
$this->_cache = new Memcached();
// libketama設定
$this->_cache->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
// memcachedサーバ設定
$result = $this->_cache->addServers(array(
array($config->memcached->{1}->host, $config->memcached->{1}->port, 50),
array($config->memcached->{2}->host, $config->memcached->{2}->port, 50),
));
// キャッシュキー
$this->_cacheNameSpace = $this->_makeCacheKey(array($this->_schema, $this->_name));
// 接続失敗の場合
if (!$result) {
throw new Exception('error memcached connection');
}
}
catch(Exception $e) {
die($e->getMessage());
}
}
/**
* キャッシュ設定
*/
public function setCache($key, $value)
{
$result = $this->_cache->set($key, $value, time() + 86400);
// 設定失敗の場合
if (!$result) {
throw new Exception('error memcached set');
}
}
/**
* キャッシュ取得
*/
public function getCache($key)
{
$result = $this->_cache->get($key);
return $result;
}
/**
* キャッシュ削除
*/
public function delCache($key)
{
$this->_cache->delete($key);
}
/**
* 全てのキャッシュを破棄する
*/
public function flushCache()
{
$this->_cache->flush();
}
/**
* キャッシュキー作成
*/
protected function _makeCacheKey($keys)
{
return implode('_', $keys);
}
}
必須ライブラリ
pecl::memcached http://php.benscom.com/manual/ja/book.memcached.php
libmemcached http://freshmeat.net/projects/libmemcached
インストール確認
$ php -R ' phpinfo(); exit(); ' | grep memcached memcached memcached support => enabled libmemcached version => 0.44 Registered save handlers => files user sqlite memcache memcached
